package bb.lanxing.lib.devices.bryton.ncs;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import androidx.legacy.content.WakefulBroadcastReceiver;
import bb.lanxing.lib.devices.bryton.bbcp.BBDevice;
import bb.lanxing.lib.devices.bryton.bbcp.BbcpManager;
import bb.lanxing.lib.devices.bryton.ncs.ExtensionManager;

public class NotificationCenterService extends Service implements ExtensionManager.OnChangeListener {
    public static final String ACTION_UPDATE_EXTENSIONS = "com.brytonsport.ncs.action.UPDATE_EXTENSIONS";
    public static final String EXTRA_COMPONENT_NAME = "com.brytonsport.ncs.extra.COMPONENT_NAME";
    public static final String EXTRA_DEVICE_ADDRESS = "com.brytonsport.ncs.extra.DEVICE_ADDRESS";
    public static final String EXTRA_UPDATE_REASON = "com.brytonsport.ncs.extra.UPDATE_REASON";
    public static final String EXTRA_USER_ADDRESS = "com.brytonsport.ncs.extra.USER_ADDRESS";
    private static final String TAG = "NotificationCenterService";
    private BbcpManager mBbcpManager;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothManager mBluetoothManager;
    private BluetoothDevice mDevice;
    private String mDeviceAddress;
    private ExtensionHost mExtensionHost;
    private ExtensionManager mExtensionManager;
    private Handler mServiceHandler;
    private Looper mServiceLooper;
    private String mUserAddress;
    private final IBinder mBinder = new LocalBinder();
    private Intent mWakefulIntent = null;
    private Handler mUpdateHandler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            NotificationCenterService.this.logi("NotificationCenterService:handleMessage");
            ComponentName componentName = (ComponentName) message.obj;
            for (ExtensionManager.ExtensionWithData extensionWithData : NotificationCenterService.this.mExtensionManager.getActiveExtensionsWithData()) {
                if (extensionWithData.listing.componentName.flattenToString().equals(componentName.flattenToString())) {
                    NotificationCenterService.this.logi("send ble notification");
                    NotificationCenterService.this.sendNotification(extensionWithData.latestData);
                }
            }
            NotificationCenterService.this.mServiceHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (NotificationCenterService.this.mWakefulIntent != null) {
                        WakefulBroadcastReceiver.completeWakefulIntent(NotificationCenterService.this.mWakefulIntent);
                        NotificationCenterService.this.logi("release the wake lock");
                    }
                }
            });
        }
    };

    @Override
    public void onExtensionsChanged(ComponentName componentName) {
        logi("onExtensionsChanged");
        this.mUpdateHandler.removeCallbacksAndMessages(null);
        Handler handler = this.mUpdateHandler;
        handler.sendMessageDelayed(handler.obtainMessage(0, componentName), 500L);
    }

    @Override
    public IBinder onBind(Intent intent) {
        logi("onBind");
        return this.mBinder;
    }

    public BbcpManager getBbcpManager() {
        if (this.mBbcpManager == null) {
            this.mBbcpManager = new BbcpManager();
        }
        return this.mBbcpManager;
    }

    protected void sendNotification(final ExtensionData extensionData) {
        if (TextUtils.isEmpty(this.mDeviceAddress)) {
            logi("null device address");
            String string = PreferenceManager.getDefaultSharedPreferences(this).getString(EXTRA_DEVICE_ADDRESS, "");
            if (TextUtils.isEmpty(string)) {
                return;
            }
            this.mDeviceAddress = string;
            logi("read from preference: deviceAddress=" + this.mDeviceAddress);
        }
        if (TextUtils.isEmpty(this.mUserAddress)) {
            logi("null user address");
            String string2 = PreferenceManager.getDefaultSharedPreferences(this).getString(EXTRA_USER_ADDRESS, "");
            if (TextUtils.isEmpty(string2)) {
                return;
            }
            this.mUserAddress = string2;
            logi("read from preference: userAddress=" + this.mUserAddress);
        }
        BluetoothDevice remoteDevice = this.mBluetoothAdapter.getRemoteDevice(this.mDeviceAddress);
        this.mDevice = remoteDevice;
        if (remoteDevice == null) {
            logi("device is null");
        } else {
            this.mServiceHandler.post(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 2; i++) {
                        if (i == 1) {
                            NotificationCenterService.this.wakeupBluetooth();
                        }
                        BbcpManager bbcpManager = NotificationCenterService.this.getBbcpManager();
                        NotificationCenterService notificationCenterService = NotificationCenterService.this;
                        notificationCenterService.logi("connect remote device: " + NotificationCenterService.this.mDeviceAddress);
                        NotificationCenterService notificationCenterService2 = NotificationCenterService.this;
                        if (bbcpManager.connect(notificationCenterService2, notificationCenterService2.mDevice) != 0) {
                            NotificationCenterService.this.loge("connect failed");
                        } else {
                            if (!BBDevice.isConnected()) {
                                NotificationCenterService notificationCenterService3 = NotificationCenterService.this;
                                notificationCenterService3.logi("write user address=" + NotificationCenterService.this.mUserAddress);
                                bbcpManager.bind(NotificationCenterService.this.mUserAddress);
                            }
                            NotificationCenterService.this.logi("send notification data");
                            boolean sendNotification = bbcpManager.sendNotification(extensionData);
                            if (!sendNotification) {
                                NotificationCenterService.this.loge("send notification failed");
                            }
                            NotificationCenterService.this.logi("disconnect");
                            bbcpManager.disconnect();
                            NotificationCenterService.this.logi("close");
                            bbcpManager.closeBluetoothGatt();
                            if (sendNotification) {
                                return;
                            }
                        }
                    }
                }
            });
        }
    }

    public class LocalBinder extends Binder {
        public LocalBinder() {
        }

        NotificationCenterService getService() {
            return NotificationCenterService.this;
        }
    }

    private void handleUpdateExtensions(Intent intent) {
        logi("execute: handleUpdateExtensions");
        int intExtra = intent.getIntExtra(EXTRA_UPDATE_REASON, 0);
        String stringExtra = intent.getStringExtra(EXTRA_COMPONENT_NAME);
        if (!TextUtils.isEmpty(stringExtra)) {
            this.mExtensionHost.execute(ComponentName.unflattenFromString(stringExtra), ExtensionHost.UPDATE_OPERATIONS.get(intExtra), 500, intExtra);
            return;
        }
        for (ComponentName componentName : this.mExtensionManager.getActiveExtensionNames()) {
            this.mExtensionHost.execute(componentName, ExtensionHost.UPDATE_OPERATIONS.get(intExtra), 500, intExtra);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int i, int i2) {
        logi("onStartCommand");
        if (intent != null) {
            if (ACTION_UPDATE_EXTENSIONS.equals(intent.getAction())) {
                String stringExtra = intent.getStringExtra(EXTRA_DEVICE_ADDRESS);
                if (!TextUtils.isEmpty(stringExtra)) {
                    this.mDeviceAddress = stringExtra;
                    PreferenceManager.getDefaultSharedPreferences(this).edit().putString(EXTRA_DEVICE_ADDRESS, this.mDeviceAddress).commit();
                }
                String stringExtra2 = intent.getStringExtra(EXTRA_USER_ADDRESS);
                if (!TextUtils.isEmpty(stringExtra2)) {
                    this.mUserAddress = stringExtra2;
                    PreferenceManager.getDefaultSharedPreferences(this).edit().putString(EXTRA_USER_ADDRESS, this.mUserAddress).commit();
                }
                handleUpdateExtensions(intent);
            }
            this.mWakefulIntent = intent;
            return 1;
        }
        return 1;
    }

    @Override
    public void onCreate() {
        logi("onCreate");
        HandlerThread handlerThread = new HandlerThread("BNCS:" + getClass().getSimpleName());
        handlerThread.start();
        this.mServiceLooper = handlerThread.getLooper();
        this.mServiceHandler = new Handler(this.mServiceLooper);
        ExtensionManager extensionManager = ExtensionManager.getInstance(this);
        this.mExtensionManager = extensionManager;
        extensionManager.addOnChangeListener(this);
        this.mExtensionHost = new ExtensionHost(this);
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService("bluetooth");
        this.mBluetoothManager = bluetoothManager;
        if (bluetoothManager == null) {
            loge("Unable to initialize BluetoothManager.");
        }
        BluetoothAdapter adapter = this.mBluetoothManager.getAdapter();
        this.mBluetoothAdapter = adapter;
        if (adapter == null) {
            loge("Unable to obtain a BluetoothAdapter.");
        }
        this.mExtensionHost.establishAndDestroyConnections(this.mExtensionManager.getActiveExtensionNames());
        PeriodicExtensionRefreshReceiver.updateExtensionsAndEnsurePeriodicRefresh(getApplicationContext());
    }

    @Override
    public void onDestroy() {
        logi("onDestroy");
        super.onDestroy();
        this.mServiceHandler.removeCallbacksAndMessages(null);
        this.mServiceLooper.quit();
        this.mUpdateHandler.removeCallbacksAndMessages(null);
        this.mExtensionManager.removeOnChangeListener(this);
        this.mExtensionHost.destroy();
    }

    public void loge(String str) {
        Log.e(TAG, str);
    }

    public void logi(String str) {
        Log.i(TAG, str);
    }

    public void wakeupBluetooth() {
        logi("wakeupBluetooth");
        BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bArr) {
            }
        };
        this.mBluetoothAdapter.startLeScan(leScanCallback);
        try {
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.mBluetoothAdapter.stopLeScan(leScanCallback);
    }
}
